package com.example.videolib

import android.view.LayoutInflater
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.baselib.BaseRepository
import com.example.baselib.activity.BaseActivity
import com.example.baselib.constants.MyConstants
import com.example.baselib.dialog.MsgDialog
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import kotlinx.android.synthetic.main.activity_vide_nick.*
import kotlinx.coroutines.*

class VideNickActivity : BaseActivity() {
    val videoRepository:VideoRepository= VideoRepository()
    private lateinit var videoNickAdapter: VideNickAdapter
    override fun layoutResId(): Int =R.layout.activity_vide_nick

    override fun initView() {
        setToolbarMsg("工业视频")
        setToolbarColor(R.color.colorDBlue, R.color.colorWhite)
        setToolbarMenu(true, R.id.menu_safe)
        videoNickAdapter =VideNickAdapter(R.layout.all_nick_item)
        val empty = LayoutInflater.from(context).inflate(R.layout.empty_item, null, false)
        videoNickAdapter.emptyView=empty
        video_nick_rcv.adapter=videoNickAdapter
//        videoNickAdapter.bindToRecyclerView(video_nick_rcv)
        video_nick_rcv.layoutManager =  LinearLayoutManager(this, LinearLayoutManager.VERTICAL,false)
    }

    override fun initData() {
        loadNickData()
    }
    private fun loadNickData() {
        GlobalScope.launch(Dispatchers.Main) {
            try {
                val result = videoRepository.loadNickData(MyConstants.userData.token)
                val type = object : TypeToken<List<Any>>() {}.type
                val list = Gson().fromJson<List<Any>>(result.body()?.data, type)
                videoNickAdapter.setNewData(list)
            } catch (e: Exception) {
                requestError(e)
            }


        }
    }

    private fun requestError(it: Exception) {
        //处理一些已知异常
        it?.run {
            when (it) {
                is TimeoutCancellationException -> {
                    MsgDialog("请求超时,请检查网络").show(
                        supportFragmentManager,
                        "TimeoutCancellationException"
                    )
                }
                is BaseRepository.RequestException -> {
                    message.toString()

                    MsgDialog(message.toString()).show(
                        supportFragmentManager,
                        "RequestException"
                    )
                }
                is CancellationException -> {
                    MsgDialog("请求取消").show(
                        supportFragmentManager,
                        "RequestException"
                    )
                }

                else -> {
                    MsgDialog("Other"+message.toString()).show(
                        supportFragmentManager,
                        "otherException"
                    )
                }
            }
        }
    }
}
